import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_module/api/news_model.dart';
import 'package:flutter_module/beans/Entity.dart';
import 'package:flutter_module/beans/EntityViewModel.dart';
import 'package:flutter_module/beans/ShareBean.dart';
import 'package:flutter_module/beans/appkey.dart';
import 'package:flutter_module/beans/conmmonResult.dart';
import 'package:flutter_module/commom/application.dart';
import 'package:flutter_module/commom/commom.dart';
import 'package:flutter_module/event/ProductContentEvent.dart';
import 'package:flutter_module/event/getysy_event.dart';
import 'package:flutter_module/event/login_event.dart';
import 'package:flutter_module/http/UserModel.dart';
import 'package:flutter_module/http/api_service.dart';
import 'package:flutter_module/http/dio_manager.dart';
import 'package:flutter_module/pages/settings/TestDemo.dart';
import 'package:flutter_module/pages/settings/machine_settings.dart';
import 'package:flutter_module/widget/buttun/IconTextButtun.dart';
import 'package:flutter_module/widget/view/LoadingDialog.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';

import '../../DemoLocalizations.dart';
// import 'package:wifi_configuration/wifi_configuration.dart';
// import 'package:wifi_iot/wifi_iot.dart';

class NewsCard extends StatelessWidget {
  final App_esp_ip model;
  final EdgeInsetsGeometry padding;
  final bool isNew;

  NewsCard(
    this.model, {
    @required this.padding,
    this.isNew = false,
  });

  @override
  Widget build(BuildContext context) {
    bool isline = model.line;
    // isline = true;
    var showtext = DemoLocalizations.of(context).RemoteOnline;
    if (!isline) {
      showtext = DemoLocalizations.of(context).offLine;
    }

    Color color = Theme.of(context).primaryColor;
//    Widget buttonSection = Container(
//      child: Row(
//        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
//        children: [
//          _buildButtonColumn(color, Icons.call, 'CALL'),
//          _buildButtonColumn(color, Icons.near_me, 'ROUTE'),
//          _buildButtonColumn(color, Icons.share, 'SHARE'),
//        ],
//      ),
//    );

    return Container(
      padding: padding,
      alignment: Alignment.center,
      width: winWidth(context),
      child: new FlatButton(
        onPressed: () {
          // model.line
          if (model.line) {
            //在此验证是否还有此设备
            entityViewModel.getEntityNews(context).then((v) {
              List data = new List();
              data = v;
              bool also = false;
              data.forEach((f) {
                if (f.chipid == model.chipid) {
                  also = true;
                }
              });
              if (also) {
                Navigator.of(context)
                    .push(new MaterialPageRoute(builder: (context) {
                  return new TestDemo(
                    model: model,
                  );
                }));
              } else {
                showToast('已失去此设备控制权，请刷新列表');
              }
            });
          } else {
            showToast(DemoLocalizations.of(context).machinenotonline);
//           showDialog(
//               context: context,
//               barrierDismissible: false,
//               builder: (BuildContext context) {
//                 return new LoadingDialog(
//                   text: "正在进行本地连接…",
//                 );
//               });
          }
        },
        /*长按*/
        onLongPress: () {
          if (model.share) {
            return;
          }
//          print("长按文本");
          showDialog(
              context: context,
              builder: (BuildContext context) {
                return CupertinoAlertDialog(
                  content: SizedBox(child: new ButtonBarLessDefault(model)),
                  actions: <Widget>[
                    CupertinoDialogAction(
                      child: Text(DemoLocalizations.of(context).cancel),
                      onPressed: () {
                        Navigator.pop(context);
//                        print("取消");
                      },
                    ),
                  ],
                );
              });
        },
        color: Colors.white,
        padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 15.0),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(5.0)),
        ),
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Wrap(
              direction: Axis.horizontal, //不设置默认为horizontal
              alignment: WrapAlignment.center, //沿主轴方向居中
              spacing: 0.0, //主轴（水平）方向间距
              runSpacing: 4.0, //纵轴（垂直）方向间距
              children: <Widget>[
                new Visibility(
                  visible: true,
                  child: new Container(
                    decoration: BoxDecoration(
                        color: isline ? Colors.green : Colors.green[50],
                        borderRadius: BorderRadius.all(Radius.circular(5.0))),
                    alignment: Alignment.center,
                    padding: EdgeInsets.symmetric(horizontal: 3.0, vertical: 2),
                    margin: EdgeInsets.only(right: 5.0),
                    child: new Text(
                      showtext,
                      style:
                          TextStyle(color: isline ? Colors.white : Colors.grey),
                    ),
                  ),
                ),
                new Row(
                  children: <Widget>[
                    new Expanded(
                        child: new Row(
                      children: <Widget>[
                        Expanded(
                          child: new Text(
                            '${model?.productName ?? '无名'}',
                            style: TextStyle(
                                color: isline ? Colors.black : Colors.black45),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        new Visibility(
                          visible: model.share,
                          child: new Text(
                            '${model.fromshareuser != null ? '(来自' + model.fromshareuser + '的分享)' : '来自分享'}',
                            textAlign: TextAlign.right,
                            style: TextStyle(color: Colors.lime),
                          ),
                        ),
                      ],
                    )),
                    new Visibility(
                      visible: !model.share,
                      child: Container(
                        alignment: Alignment.center,
                        child: MaterialButton(
                          padding: EdgeInsets.all(2),
                          onPressed: () {
                            showDialog(
                                context: context,
                                builder: (BuildContext context) {
                                  return CupertinoAlertDialog(
                                    content: SizedBox(
                                        child: new ButtonBarLessDefault(model)),
                                    actions: <Widget>[
                                      CupertinoDialogAction(
                                        child: Text("取消"),
                                        onPressed: () {
                                          Navigator.pop(context);
                                          print("取消");
                                        },
                                      ),
                                    ],
                                  );
                                });
                          },
                          child: Container(
                            alignment: Alignment.centerRight,
                            padding: const EdgeInsets.all(3.0),
                            child: Column(
                              children: <Widget>[
                                Icon(
                                  Icons.reorder,
                                  color: Colors.blueAccent,
                                ),
                                Text('set'),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}

showModalBottomSheet(BuildContext context) {
  showBottomSheet(
    context: context,
    builder: (context) => ListView(
        // 生成一个列表选择器
        children: List.generate(
      5,
      (index) => InkWell(
          child: Container(
              alignment: Alignment.center,
              height: 60.0,
              child: Text('Item ${index + 1}')),
          onTap: () {
            print('tapped item ${index + 1}');
            Navigator.pop(context);
          }),
    )),
  );
}

/*
* ButtonBar 默认的实例,无状态
* */
class ButtonBarLessDefault extends StatelessWidget {
//  final widget;
//  final parent;
  final App_esp_ip model;

//this.widget, this.parent,
  const ButtonBarLessDefault([this.model]) : super();

  @override
  Widget build(BuildContext context) {
    TextEditingController loginEmailController = new TextEditingController();
    TextEditingController fenxiangrenname = new TextEditingController();
    var _receiveNotification;
    var _limiteNotification;
    var _limiteNotificationNumber = 0;
    var a = DateTime.now().add(new Duration(days: 1)).millisecondsSinceEpoch;
    return Container(
        margin: EdgeInsets.symmetric(vertical: 6.0),
        height: 200.0,
        child: Scrollbar(
            child: ListView(scrollDirection: Axis.vertical, // 水平listView
                children: <Widget>[
              MaterialButton(
                child: Text(DemoLocalizations.of(context).UnbindDevice),
                color: Colors.blueAccent,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5),
                ),
                onPressed: () {
                  Navigator.pop(context);
//                  print("解绑此设备");
                  showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return CupertinoAlertDialog(
//                          title: Text("不可逆操作提示"),
                          content: SizedBox(
                            child:
                                Text(DemoLocalizations.of(context).sureunbind),
                          ),
                          actions: <Widget>[
                            CupertinoDialogAction(
                              child: Text(DemoLocalizations.of(context).cancel),
                              onPressed: () {
                                Navigator.pop(context);
//                                print("取消");
                              },
                            ),
                            CupertinoDialogAction(
                              child:
                                  Text(DemoLocalizations.of(context).confirm),
                              onPressed: () {
//                                print("确定");
                                showDialog(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (BuildContext context) {
                                      return new LoadingDialog(
                                        text: DemoLocalizations.of(context)
                                            .MachineUnbinding,
                                      );
                                    });
                                ApiService().deleteBychipid(
                                    (Response response) {
                                  if (response != null) {
                                    ConmmonResult conmmonResult =
                                        ConmmonResult.fromJson(response.data);
                                    if (conmmonResult.success) {
                                      Application.eventBus
                                          .fire(new LoginEvent());
                                      showToast(DemoLocalizations.of(context)
                                          .deletionSucceeded);
                                      Navigator.pop(context);
                                      Navigator.pop(context);
                                    } else {
                                      showToast(conmmonResult.message);
                                      Navigator.pop(context);
                                    }
                                  }
                                }, model.chipid);
                              },
                            ),
                          ],
                        );
                      });
                },
              ),
              MaterialButton(
                child: Text(DemoLocalizations.of(context).RenameDevice),
                color: Colors.blueAccent,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5),
                ),
                onPressed: () {
                  Navigator.pop(context);
//                  print("重命名此设备");
                  showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return CupertinoAlertDialog(
//                          title: Text("不可逆操作提示"),
                          content: Card(
                            elevation: 0.0,
                            child: Column(
                              children: <Widget>[
                                TextField(
                                  controller: loginEmailController,
                                  decoration: InputDecoration(
                                    hintText: DemoLocalizations.of(context)
                                        .enternewname,
                                    filled: true,
                                  ),
                                ),
                              ],
                            ),
                          ),

                          actions: <Widget>[
                            CupertinoDialogAction(
                              child: Text(DemoLocalizations.of(context).cancel),
                              onPressed: () {
                                Navigator.pop(context);
//                                print("取消");
                              },
                            ),
                            CupertinoDialogAction(
                              child:
                                  Text(DemoLocalizations.of(context).confirm),
                              onPressed: () {
                                print(loginEmailController.text);
                                model.productName = loginEmailController.text;
//                                print("确定");
                                ApiService().ESPEDIT((Response response) {
                                  if (response != null) {
                                    ConmmonResult conmmonResult =
                                        ConmmonResult.fromJson(response.data);
                                    if (conmmonResult.success) {
                                      showToast(conmmonResult.message);
                                      Navigator.pop(context);
                                    } else {
                                      showToast(conmmonResult.message);
                                    }
                                  }
                                }, model);
                              },
                            ),
                          ],
                        );
                      });
                },
              ),
              MaterialButton(
                child: Text(DemoLocalizations.of(context).ShareDevice),
                color: Colors.blueAccent,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5),
                ),
                onPressed: () {
                  Navigator.pop(context);
//                  print("重命名此设备");
                  showDialog(
                      context: context,
                      builder: (context) {
                        String label = 'test';
                        return StatefulBuilder(
                          builder: (context, state) {
                            print('label = $label');
                            return CupertinoAlertDialog(
//                                            title: Text("不可逆操作提示"),
                              content: Card(
                                elevation: 0.0,
                                child: Column(children: <Widget>[
                                  TextField(
                                    textAlign: TextAlign.center,
                                    controller: fenxiangrenname,
                                    inputFormatters: [
                                      WhitelistingTextInputFormatter(
                                          RegExp("[a-z0-9]")), //只允许输入字母
                                    ],
                                    decoration: InputDecoration(
                                      hintText: DemoLocalizations.of(context)
                                          .entershareraccount,
                                      filled: false,
                                    ),
                                  ),
                                  FlatButton(
                                      onPressed: () {
                                        _onClick((String response) {
                                          print(response);
                                          var now = DateTime.parse(response);
                                          a = now.millisecondsSinceEpoch; // 时间戳
                                          print(a);
                                          state(() {
                                            _receiveNotification =
                                                now.toString().substring(0, 16);
                                          });
                                        }, context);
                                      },
                                      child: Text(
                                        '${_receiveNotification ?? DemoLocalizations.of(context).clicktime}',
                                        style: TextStyle(color: Colors.blue),
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                      )),
                                  Divider(
                                    height: 4.0,
                                    color: Colors.black,
                                  ),
                                  Center(
                                    child: PopupMenuButton(
                                      child: Container(
                                        alignment: Alignment.center,
                                        height: 46,
                                        child: Text(
                                        _limiteNotification ??
                                            DemoLocalizations.of(context)
                                                .clickpermission,
                                        style: TextStyle(color: Colors.blue),
                                      ),),
//                                            tooltip: "长按提示",
                                      initialValue: "hot",
                                      padding: EdgeInsets.all(4.0),
                                      itemBuilder: (BuildContext context) {
                                        return <PopupMenuItem<String>>[
                                          
                                          PopupMenuItem<String>(
                                            child: Text(
                                                DemoLocalizations.of(context)
                                                    .ControlSwitch),
                                            value: "0",
                                          ),
                                          PopupMenuItem<String>(
                                            child: Text(
                                                DemoLocalizations.of(context)
                                                    .SettingParameters),
                                            value: "1",
                                          ),
//                                                          PopupMenuItem<String>(child: Text("恢复出厂设置"), value: "2",),
                                          PopupMenuItem<String>(
                                            child: Text(
                                                DemoLocalizations.of(context)
                                                    .ViewCamera),
                                            value: "2",
                                          ),
                                        ];
                                      },
                                      onSelected: (String action) {
                                        switch (action) {
                                          case "0":
//                                                            print("控制开关");
                                            _limiteNotification =
                                                DemoLocalizations.of(context)
                                                    .ControlSwitch;
                                            _limiteNotificationNumber = 0;
                                            break;
                                          case "1":
//                                                            print("设置参数");
                                            _limiteNotification =
                                                DemoLocalizations.of(context)
                                                    .SettingParameters;
                                            _limiteNotificationNumber = 1;
                                            break;
                                          case "2":
//                                                            print("查看摄像头");
                                            _limiteNotification =
                                                DemoLocalizations.of(context)
                                                    .ViewCamera;
                                            _limiteNotificationNumber = 2;
                                            break;
                                          case "3":
//                                                            print("查看摄像头");
                                            _limiteNotification =
                                                DemoLocalizations.of(context)
                                                    .ViewCamera;
                                            _limiteNotificationNumber = 3;
                                            break;
                                        }
                                        state(() {});
                                      },
                                      onCanceled: () {
//                                              print("onCanceled");
                                      },
                                    ),
                                  ),
                                ]),
                              ),

                              actions: <Widget>[
                                CupertinoDialogAction(
                                  child: Text(
                                      DemoLocalizations.of(context).cancel),
                                  onPressed: () {
                                    Navigator.pop(context);
//                                                  print("取消");
                                  },
                                ),
                                CupertinoDialogAction(
                                  child: Text(
                                      DemoLocalizations.of(context).confirm),
                                  onPressed: () {
                                    print(fenxiangrenname.text);
                                    if (fenxiangrenname.text.isEmpty) {
                                      showToast(DemoLocalizations.of(context)
                                          .enterSharerAccount);
                                      return;
                                    }
//                                                  print("确定");
                                    ShareBean shareBean = new ShareBean();
                                    shareBean.level = _limiteNotificationNumber;
                                    shareBean.chipid = model.chipid;
                                    shareBean.heAccount = fenxiangrenname.text;
                                    shareBean.time = a;
                                    shareBean.myAccount = model.appUuid;
                                    // SHARE
                                    ApiService().ShareESP((Response response) {
                                      if (response != null) {
                                        ConmmonResult conmmonResult =
                                            ConmmonResult.fromJson(
                                                response.data);
                                        if (conmmonResult.success) {
                                          showToast(
                                              DemoLocalizations.of(context)
                                                  .shareSuccess);
                                          Navigator.pop(context);
                                        } else {
                                          showToast(conmmonResult.message);
                                        }
                                      }
                                    }, shareBean, false);
                                  },
                                ),
                              ],
                            );
                          },
                        );
                      });
                },
              ),
//              MaterialButton(child: Text('进行本地连接'),
//                color: Colors.blueAccent,
//                shape: RoundedRectangleBorder(
//                  borderRadius: BorderRadius.circular(5),
//                ),
//                onPressed: () async {
//                  WiFiForIoTPlugin.connect("note",
//                      password: "999988881",
//                      joinOnce: true,
//                      security: NetworkSecurity.WPA);
////                  WifiConnectionStatus connectResult = await WifiConfiguration.connectToWifi(
////                      "note", "999988881", "com.example.flutter_module.host");
////                  print("is Connected : ${connectResult}");
//                },),
              MaterialButton(
                child: Text(DemoLocalizations.of(context).AddCamera),
                color: Colors.blueAccent,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5),
                ),
                onPressed: () {
                  Navigator.pop(context);
//                  print("添加摄像头");
                  if (model.ysyappkey != null) {
                    if (model.ysyappkey.isNotEmpty) {
                      showToast(DemoLocalizations.of(context).haveAddCamera);
                      return;
                    } else {}
                  } else {}

                  iOSPushToVC1();
                },
              ),
            ])));
  }

  // 创建一个给native的channel (类似iOS的通知）
  static const MethodChannel methodChannel =
      MethodChannel('com.flutter.io/video');

  iOSPushToVC1() async {
    //添加摄像头
    ApiService().getYsyToekn((Appkey appkey) async {
      if (appkey != null) {
        if (appkey.success) {
          print(appkey);
          Application.eventBus.fire(new YsyEvent(appkey.result.appkey, model));
          Map<String, dynamic> map = {
            "EzvizAppKey": appkey.result.appkey,
            "AccessToken": appkey.result.accessToken,
            "DevSerial": "C98301385"
          };
          await methodChannel.invokeMethod('iOSFlutter1', map);
        } else {
          showToast(appkey.message);
        }
      }
    });
  }
}

_onClick(Function callback, BuildContext context) {
  if (Platform.localeName.startsWith('en')) {
    DatePicker.showDateTimePicker(context,
        showTitleActions: true,
        minTime: DateTime.now(),
        maxTime: DateTime(2109, 6, 7, 1, 1, 1), onChanged: (date) {
      print('change $date');
    }, onConfirm: (date) {
      print('confirm $date');
      callback(date.toString());
    }, currentTime: DateTime.now(), locale: LocaleType.en);
  } else {
    DatePicker.showDateTimePicker(context,
        showTitleActions: true,
        minTime: DateTime.now(),
        maxTime: DateTime(2109, 6, 7, 1, 1, 1), onChanged: (date) {
      print('change $date');
    }, onConfirm: (date) {
      print('confirm $date');
      callback(date.toString());
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }
}

//void deleteDevice(Function callback, String id) async {
//  DioManager.singleton.dio
//      .get(API.deleteDevice+id)
//      .then((response) {
//    print(response.toString());
//    callback(response);
//  });
//}

class CurrentIndexProvide with ChangeNotifier {
  int currentIndex = 0;
  changeIndex(int newIndex) {
    currentIndex = newIndex;
    notifyListeners();
  }
}
